﻿using Order.Common.Dapper;
using System;
using System.Collections.Generic;
using System.Text;
using Dapper;
using Order.Domain;
using System.Linq;
using System.Text.Json;
using Order.Domain.DomainEvent;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;
using Order.Common.IocHelper;

namespace Order.Common
{
    /// <summary>
    /// 获取EventStorage中的领域事件
    /// </summary>
    public class EventStorageRepository
    {
        private readonly string ConnectionStr = "Data Source=DESKTOP-G8UTIT6\\LI;Initial Catalog=Conference;User ID=sa;Password=123456li;Max Pool Size = 512;MultipleActiveResultSets=true";

        public async Task<List<IDomainEvent>> GetAggregateRootEventStorageById(Guid AggregateRootId)
        {
            try
            {
                using (var connection = new SqlConnection(ConnectionStr))
                {
                    var eventStorageList = await connection.QueryAsync<EventStorage>($"SELECT * FROM dbo.EventStorageInfo WHERE AggregateRootId='{AggregateRootId}'");
                    List<IDomainEvent> domainEventList = new List<IDomainEvent>();
                    foreach (var item in eventStorageList)
                    {
                        var dictionaryDomainEvent = JsonConvert.DeserializeObject<Dictionary<string, string>>("");
                        foreach (var entry in dictionaryDomainEvent)
                        {
                            var domainEventType = TypeNameProvider.GetType(entry.Key);
                            if (domainEventType != null)
                            {
                                var domainEvent = JsonConvert.DeserializeObject(entry.Value, domainEventType) as IDomainEvent;
                                domainEventList.Add(domainEvent);
                            }
                        }
                    }
                    return domainEventList;
                }
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {
                throw;
            }
        }


    }

}
